package com.imooc.activitiweb.security;

import com.imooc.activitiweb.mapper.UserInfoBeanMapper;
import com.imooc.activitiweb.pojo.UserInfoBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

@Component
@Configuration
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserInfoBeanMapper userInfoBeanMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 登陆密码  需要进行加密
        /*String password = passwordEncoder().encode("666");
        return new User(username,   // 用户名，现在没有查数据库所以前端可以随便写
                         password,   // 密码必须为  666
                         // activiti 7 需要用户必须拥有 ROLE_ACTIVITI_USER 角色
                         AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_ACTIVITI_USER"));*/

        /**
         * 需要做的操作
         *      读取数据库判断用户
         *      如果用户是 null 抛出异常
         *      返回用户信息
         */
        UserInfoBean userInfoBean = userInfoBeanMapper.selectByUsername(username);
        if(userInfoBean == null){
            throw new UsernameNotFoundException("用户不存在！");
        }
        // 返回用户信息，密码比对不只是在这里进行比对的
        // 我们将查询到的用户信息返回给框架，然后安全框架内部根据用户输入的密码和查询的密码进行比对
        return userInfoBean;
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
